#!/bin/awk -f
## select tiling number from tilings.out
BEGIN{
#  sel=ARGV[1]; ARGV[1]="-"; ARGC=2;
  show2d=0;
}
FNR==1{
  nn=$1; mu=$2; nt=$3;
#  nt=10;
#  print nn,mu,nt;
}
FNR>1&&FNR<4{ba=ba$0"\n"} #basis
FNR==3{
#  print nn,mu;
  nnl=nn/mu;
  for(i=1;i<=nt;i++){ # tilings
#    print "tiling "i > "/dev/stderr";    
    for(k=1;k<=mu;k++){ # layers
#      print "layer "k;
      ss[k]=""; st[k]="";
      for(j=1;j<=nnl;j++){ # nodes
	getline;
	nu=nuoffs($0);
	for(l=1;l<=5;l++){
	  ss[k]=ss[k]""$l;
	  if(l<5){
	    ss[k]=ss[k]" ";
	  }else{
	    ss[k]=ss[k]"   "nu"\n";
	  }
	}
	if(nu==2){
	  for(l=1;l<=5;l++){
	    st[k]=st[k]""$l;
	    if(l<5){
	      st[k]=st[k]" ";
	    }else{
	      st[k]=st[k]"\n";
	    }
	  }
	}
      }
    }
    s=""; t="";
    d2=1;
    for(k=2;k<=mu;k++){ # layers : check if this is flat or not
      if(st[1]!=st[k]){d2=0}
    }
    if(d2==0||mu==1){
      for(k=1;k<=mu;k++){ # again layers
	s=s""ss[k];
	t=t""st[k];
      }
      n[t]++; 
      if(n[t]==1){
	mt++;
	ti[t]=s;
	if(mu==2){
	  l1[mt]=st[1];
	  l2[mt]=st[2];
	}
      }
    }else{ # these are pseudostacks AA...
      s=ss[1];
      t=st[1];
      n2[t]++;
      if(n2[t]==1){
	mt2++;
	ti2[t]=s;
	ll[mt2]=st[1];
      }
    };
  }
}
END{
  split(FILENAME,a,".");
  rep=a[1]".tsta";
  mrep=a[1]".tm";
  out=a[1]".sel";
  out2=a[1]".sel2";
  if(mu==2){
    for(i=1;i<=mt;i++){
      for(j=1;j<=mt2;j++){
	for(k=1;k<=mt2;k++)if(j!=k){
	  bil=l1[i]""l2[i];
	  cb1=ll[j]""ll[k];
	  cb2=ll[k]""ll[j];
	  if(bil==cb1){
	    mm[j,k]=i;
	    px[i]++;
#	    print "bistack "i" "j"-"k >>rep;
	  }
	}
      }
    }
    nr=0; for(i=1;i<=mt;i++)if(px[i]==""){nr++};
    print "dim = "mt2 > mrep;
    mf=1; if(mt>9){mf=2};if(mt>99){mf=3};if(mt>999){mf=4};
    for(j=1;j<=mt2;j++){
      for(k=1;k<=mt2;k++){
	if(k>j){
	  kj=(mm[k,j]!=""); jk=(mm[j,k]!="");
	  if(kj!=jk){asym++}
	}
	if(j!=k){
	  ix=mm[j,k];
	}else{
	  ix=j;
	};
	printf("%"mf"i ",ix)>>mrep;
      }
      printf("\n")>>mrep;
    }
  }
  if(asym>0){print "transpose-sym-break : "asym}
  i=0; for(x in n){i++};
  print i" tilings -> "out" ("nr" unregistered)";
  print i" tilings -> "out" ("nr" unregistered)" > rep;
  i=0; for(x in n){
    i++;
    print i,n[x]>>rep;
  };
  print nn,mu,i" # sort+stat: out of "nt>out;
  printf ba>>out;
  for(x in n){
    printf ti[x]>>out;
  };
  if(mu>1){
    i=0; for(x in n2){i++};
    print i" mono-layer tilings -> "out2;
    print "#### found "i" mono-layer tilings -> "out2 >> rep;
    i=0; for(x in n2){
      i++;
      print i,n2[x]>>rep;
    };
    print nnl,"1",i" # sort+stat: selected flat 1-layer tilings">out2;
    printf ba>>out2;
    for(x in n2){
      printf ti2[x]>>out2;
    };
  };
}
function nuoffs(x, a,i,mn){
  split(x,a); mn=2;
  for(i=1;i<=5;i++){
    mn+=a[i];
  }
  if(mn<0){mn=-mn};
  while(mn>2){
    mn-=5;
  }
  if(mn<0){mn=-mn}
  return mn;
}
